package com.letv.business.flow.PlayFlowModule;

import android.os.Handler;

import com.ledim.app.LeDimApplication;
import com.ledim.utils.LogUtil;
import com.letv.android.client.LetvSDK;
import com.letv.android.young.client.R;
import com.letv.business.flow.album.AlbumPlayFlow;
import com.letv.business.flow.album.AlbumPlayFlowObservable;
import com.letv.business.flow.album.model.AlbumPlayInfo;
import com.letv.core.api.LetvRequest;
import com.letv.core.api.MediaAssetApi;
import com.letv.core.bean.DataHull;
import com.letv.core.bean.TimestampBean;
import com.letv.core.bean.VideoPlayerBean;
import com.letv.core.constant.PlayConstant;
import com.letv.core.db.PreferencesManager;
import com.letv.core.network.volley.VolleyRequest;
import com.letv.core.network.volley.VolleyResponse;
import com.letv.core.network.volley.toolbox.SimpleResponse;
import com.letv.core.network.volley.toolbox.VolleyNoCache;
import com.letv.core.parser.VideoPlayerParser;
import com.letv.core.utils.LogInfo;
import com.letv.datastatistics.DataStatistics;
import com.letv.datastatistics.util.LetvErrorCode;

/**
 * Created by jipengfei on 2016/11/11.
 */
public class NetworkManager {

    private requestVFListener  mVFListener;
    public  interface  requestVFListener{
        void requestVFSuccess(VideoPlayerBean result, DataHull hull);
        void requestVFFailure(VolleyResponse.NetworkResponseState state);
}

    public Handler mVFhandler = new Handler();

    public  void  requestVF(AlbumPlayFlow albumPlayFlow){
        final AlbumPlayFlow playFlow =  albumPlayFlow;
        final String ALBUM_FLOW_TAG = "albumFlowTag_";
         final String REQUEST_VIDEO_PLAY_URL = ALBUM_FLOW_TAG + "videoPlayUrl";
        final AlbumPlayInfo mPlayInfo = playFlow.getPlayInfo();
        playFlow.addPlayInfo("开始请求合并接口", "");
        LogUtil.e("开始请求合并接口");
        if (playFlow.getCid() == 0 && playFlow.getAid() == 0 && playFlow.getZid() == 0 && playFlow.getVid() == 0) {

            albumPlayFlow.getLoadListener().requestError(albumPlayFlow.getContext().getString(R.string.commit_error_info), PlayConstant.PlayErrCode.PARAMS_ERROR);
            albumPlayFlow.getObserver().notifyObservers(new AlbumPlayFlowObservable.PlayErrorCodeNotify(PlayConstant.PlayErrCode.PARAMS_ERROR, true));

            return;
        }

        final String uid = PreferencesManager.getInstance(playFlow.getContext()).getUserId();
        final String tm = String.valueOf(TimestampBean.getTm().getCurServerTime());
        String url = MediaAssetApi.getInstance(LeDimApplication.getInstance())
                .getVideoPlayUrl(playFlow.getContext(),
                        playFlow.getCid() + "",
                        playFlow.getAid() + "",
                        playFlow.getZid() + "", playFlow.getVid() + "", uid, LetvSDK.getInstance()
                                .getVideoFormat(), "0", tm);

        playFlow.getPlayInfo().videoDispatchConsumeTime = System.currentTimeMillis();
        playFlow.getPlayInfo().canPlayConsumeTime = System.currentTimeMillis();
        // 接口起始时间（统计动作22 type7使用）
        playFlow.getPlayInfo().albumPayConsumeTime = System.currentTimeMillis();

        new LetvRequest<VideoPlayerBean>(playFlow.getContext()).setUrl(url)
                .setMaxRetries(2)
                .setCache(new VolleyNoCache())
                .setParser(new VideoPlayerParser())
                .setTag(REQUEST_VIDEO_PLAY_URL)
                .setCallback(new SimpleResponse<VideoPlayerBean>() {

                    @Override
                    public void onNetworkResponse(
                            VolleyRequest<VideoPlayerBean> request,
                            final VideoPlayerBean result,
                            final DataHull hull,
                            VolleyResponse.NetworkResponseState state) {
                        mPlayInfo.mRetryNum =
                                request.getRetryPolicy()
                                        .getRetries();
                        mPlayInfo.videoDispatchConsumeTime =
                                System.currentTimeMillis() -
                                        mPlayInfo.videoDispatchConsumeTime;
                        mPlayInfo.albumPayConsumeTime =
                                System.currentTimeMillis() -
                                        mPlayInfo.albumPayConsumeTime ;
                        LogInfo.log("sguotao",
                                "****************请求合并接口消耗时间" +
                                        mPlayInfo.albumPayConsumeTime +
                                        "毫秒****************");
                        if (state ==
                                VolleyResponse.NetworkResponseState.SUCCESS) {
                            playFlow.addPlayInfo("请求合并接口成功", "");
//                            onSuccess(result, hull);
                            LogInfo.log("sguotao", "状态机请求合并接口成功:");

                            final boolean post = mVFhandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    if (mVFListener != null) {
                                        mVFListener.requestVFSuccess(result, hull);
                                    }
                                }
                            });
                        } else {
                            playFlow.addPlayInfo("请求合并接口失败",
                                    state + "");
                            LogInfo.log("sguotao", "状态机请求合并接口失败:");

                            final VolleyResponse.NetworkResponseState errState = state;
                            final boolean post = mVFhandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    if (mVFListener != null) {
                                        mVFListener.requestVFFailure(errState);
                                    }
                                }
                            });
                        }
                    }

                    @Override
                    public void onErrorReport(
                            VolleyRequest<VideoPlayerBean> request,
                            String errorInfo) {
                        DataStatistics.getInstance()
                                .sendErrorInfo(playFlow.getContext(), "0", "0", LetvErrorCode.LTURLModule_UC_MovieAvaiable, null, errorInfo, null, null, null, null);
                    }

                })
                .add();




    }

    public void setRequestVFListener(requestVFListener listener) {
        this.mVFListener = listener;
    }




}
